<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
    #box1
    {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
    }
    </style>

    <script type="text/javascript">
    //使div可以根据不同的方向键向不同的方向移动
    //按左键，div向左移
    //按右键，div向右移
    //key是键盘字符 keyCode是键盘字符代码
    window.onload=function()
    {
        var box1=document.getElementById("box1");
        //开启一个定时器，来控制div的移动
        var speed=20;
        //创建一个变量表示方向
        var dir;
        //通过修改dir来影响移动的方向
        setInterval(function()
        {
            switch(dir)
            {
                
                case "ArrowUp":
                //console.log("向上");
                box1.style.top=box1.offsetTop-speed+"px";
                break;

                case "ArrowRight":
                //console.log("向右");
                box1.style.left=box1.offsetLeft+speed+"px";
                break;

                case "ArrowDown":
                //console.log("向下");
                box1.style.top=box1.offsetTop+speed+"px";
                break;

                case "ArrowLeft":
                //console.log("向左");
                box1.style.left=box1.offsetLeft-speed+"px";
                break;
            }
        },30);

        
        //先给documment绑定一个按键按下事件
        document.onkeydown=function(event)
        {
            dir=event.key;

            //当用户按了ctrl时，速度加快
            if(event.ctrlKey)
            {
                speed=50;
            }
            else
            {
                speed=20;
            }
        };

        //当按键松开时，div不再移动
        document.onkeyup=function()
        {
            //设置方向为0
            dir=0;
        };
    };
    </script>
</head>
<body>
    <div id="box1"></div>
</body>
</html>